<?php
	/**
	Some purely back-end code for editing a teacher's profile.
	This does some error checking on the password and then tries to modify
	the account of the currently-logged-in user according to the data
	available.
	
	@author Chad Estioco
	@version Second Semester, AY 2010-2011
	*/
	session_start();
	include("checkProfile.php");
	include("write_functions.php");
	connect("localhost", "root", "", "gradegriddatabase");
	include("fetchData.php");
	
	$data=fetchAccountDetails();
	
	if(isset($_POST["toggle"])){
		$username = $_SESSION["username"];
		$account_query = mysql_query("SELECT * FROM account WHERE username = '$username'");
		$account_array = mysql_fetch_array($account_query);
		$accountid = mysql_real_escape_string($account_array["account_id"]);
		$email = mysql_real_escape_string($_POST["email"]);
		$firstname = mysql_real_escape_string($_POST["fname"]);
		$middlename = mysql_real_escape_string($_POST["mname"]);
		$lastname = mysql_real_escape_string($_POST["lname"]);
		$sex = $_POST["sex"];
		$month = (int) $_POST["months"];
		$day = (int) $_POST["dates"];
		$year = (int) $_POST["years"];
		$birthday = date("Y-m-d", mktime(0, 0, 0, $month, $day, $year));
		$contactnumber = mysql_real_escape_string($_POST["num"]);
		$country = mysql_real_escape_string($_POST["country"]);
		$city = mysql_real_escape_string($_POST["city"]);
		$municipality = mysql_real_escape_string($_POST["municipality"]);
		$street = mysql_real_escape_string($_POST["street"]);
		
		$old_password = $account_array["password"];
		$submitted_password = sha1($_POST["pwd"]);
		
		if($_POST["pwd"] != "" && $old_password != $submitted_password){
			echo "<script type='text/javascript' language='javascript'>\n";
			echo "alert('Password incorrect')\n";
			echo "window.history.back()\n";
			echo "</script>\n";
		} else{
			$new_password;
			if(isset($_POST["npwd"])){
				$new_password = mysql_real_escape_string(sha1($_POST["npwd"]));
			} else{
				$new_password = $old_password;
			}
			
			modifyaccount($accountid, $email, $username, $new_password, $firstname,
			              $middlename, $lastname, $sex, $birthday, $contactnumber,
						  $country, $city, $municipality, $street);
			
			echo "<script type='text/javascript' language='javascript'>\n
					alert('Account updated')\n
					window.history.back()\n
				  </script>\n";
		}
	}
?>